package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"ylb/entity"
	"ylb/service"
	"ylb/service/impl"
	"ylb/tool"
)

type EmailController struct {
	emailService service.EmailService
}

func NewEmailController(gin *gin.Engine) EmailController {
	controller := EmailController{}
	controller.emailService = impl.EmailServiceImpl{}
	controller.EmailRouter(gin)
	return controller
}

func (es EmailController) EmailRouter(gin *gin.Engine) {

	group := gin.Group("/email")
	{
		group.POST("/send", es.sendEmail)
	}

}
func (es EmailController) sendEmail(ctx *gin.Context) {

	var m = map[string]string{}
	err := ctx.BindJSON(&m)

	receiver := m["receiver"]
	if err != nil || receiver == "" {
		ctx.JSON(http.StatusOK, tool.Error("缺少接受", gin.H{}))
		return
	}
	err = es.emailService.SendCodeAndSetRedis("YNote验证码", "注册验证码", receiver, service.GetEmailRegisterCodeKey(receiver))
	if err != nil {
		fmt.Println(err)
		ctx.JSON(http.StatusOK, tool.Error("发送失败", gin.H{}))
		return
	}
	ctx.JSON(http.StatusOK, tool.Success("发送成功", gin.H{}))
}

func (es EmailController) sendUpdatePwd(ctx *gin.Context) {

	var m = map[string]string{}
	err := ctx.BindJSON(&m)
	if err != nil {
		fmt.Printf("%v\n", err)

		return
	}
	receiver := m["receiver"]
	if err != nil || receiver == "" {
		ctx.JSON(http.StatusOK, tool.Error("缺少接受", gin.H{}))
		return
	}
	ret, err := tool.ParseHtml("./static/html/updatePwd").Html()
	if err != nil {
		fmt.Printf("%v\n", "读取updatePwd.html失败")
		return

	}
	es.emailService.SendDefault(entity.Email{
		Subject: "YNote修改密码",
		Body:    ret,
		Receiver: []string{
			receiver,
		},
	})
	ctx.JSON(http.StatusOK, tool.Success("发送成功", gin.H{}))

}
